﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CaylayTree
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            graphics = this.CreateGraphics();
        }

        private Graphics graphics;
        private Pen pen = new Pen(Color.Black);
        private int n = 10; // 递归深度
        private double leng = 100; // 主干长度
        private double per1 = 0.6; // 右分支长度比
        private double per2 = 0.7; // 左分支长度比
        private double th1 = 30 * Math.PI / 180; // 右分支角度
        private double th2 = 20 * Math.PI / 180; // 左分支角度


        private void DrawCayleyTree(int n, double x0, double y0, double leng, double th)
        {
            if (n == 0)
                return;
            double x1 = x0 + leng * Math.Cos(th);
            double y1 = y0 + leng * Math.Sin(th);
            DrawLine(x0, y0, x1, y1);
            DrawCayleyTree(n - 1, x1, y1, per1 * leng, th + th1);
            DrawCayleyTree(n - 1, x1, y1, per2 * leng, th - th2);
        }

        private void DrawLine(double x0, double y0, double x1, double y1)
        {
            graphics.DrawLine(pen, (int)x0, (int)y0, (int)x1, (int)y1);
        }

        private void btndraw_Click(object sender, EventArgs e)
        {
            graphics.Clear(Color.White);
            DrawCayleyTree(n, 300, 500, leng, -Math.PI / 2);
        }

        private void numRecursionDepth_ValueChanged(object sender, EventArgs e)
        {
            n = (int)numRecursionDepth.Value;
        }

        private void numTrunkLength_ValueChanged(object sender, EventArgs e)
        {
            leng = (double)numTrunkLength.Value;
        }

        private void numRightBranchLengthRatio_ValueChanged(object sender, EventArgs e)
        {
            per1 = (double)numRightBranchLengthRatio.Value/100;
        }

        private void numLeftBranchLengthRatio_ValueChanged(object sender, EventArgs e)
        {
            per2 = (double)numLeftBranchLengthRatio.Value/100;
        }

        private void numRightBranchAngle_ValueChanged(object sender, EventArgs e)
        {
            th1 = (double)numRightBranchAngle.Value * Math.PI / 180;
        }

        private void numLeftBranchAngle_ValueChanged(object sender, EventArgs e)
        {
            th2 = (double)numLeftBranchAngle.Value * Math.PI / 180;
        }

        private void btnColor_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                pen.Color = colorDialog.Color;
            }
        }
    }
}
